<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;
use Illuminate\Support\Str;

class PageCacheMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $uri = $request->getRequestUri();
        list($name, $id) = explode('/', trim($uri, '/'), 2);
        $folder = public_path('cache-page');
        $file = sprintf("%s/product_%d.html",$folder, $id);
        if (file_exists($file)) {
            echo require_once $file;die;
        }
        if (!file_exists($folder)) {
            mkdir($folder);
        }
        $response = $next($request);
        if ($response instanceof Response) {
            $html = $response->getContent();
            file_put_contents($file, $html);
        }
        return $response;
    }
}
